/**
 * 用户自定义托盘图标设置
 */

import { app, Menu, Tray, nativeImage, dialog } from 'electron';
import { join, relative } from 'path';
import icon from '../../resources/tray/icon_16.png?asset';
import quit from '../../resources/tray/quit_16.png?asset';
import setting from '../../resources/tray/setting_16.png?asset';
import regards from '../../resources/tray/regards_16.png?asset';
let tray = null;

export default function (mainWindow) {

    // 创建托盘图标
    // const iconImage = nativeImage.createFromPath((app.isPackaged?'resources/app.asar.unpacked/':'')+'resources/icon_16.png');
    tray = new Tray(icon);

    // 创建托盘菜单
    const contextMenu = Menu.buildFromTemplate([
        {
            icon,
            label: '打开', click: () => showMainWindow(mainWindow)
        },
        {
            icon:setting,
            label: '设置', click: () => { }
        },
        {
            icon:regards,
            label: '关于', click: () => { }
        },
        {
            icon:quit,
            label: '退出', click: () => appQuit()
        }
    ]);

    // 设置托盘菜单
    tray.setToolTip('方块派对 - Blocks Party');
    tray.setContextMenu(contextMenu);

    // 绑定单击托盘图标事件
    tray.on('click', () => {
        // 执行单击托盘图标的操作
        // 例如，显示或隐藏应用窗口
        showMainWindow(mainWindow);
    });

}

// 还原窗口
function showMainWindow(mainWindow) {
    if (mainWindow) {
        if (mainWindow.isMinimized()) {
            mainWindow.restore();
        }
        mainWindow.show();
    }
}

// 询问app是否退出
function appQuit() {
    // 弹出提示是否真正的退出
    dialog.showMessageBox({
        type: 'warning',
        buttons: ['确定', '取消'],
        defaultId: 0,
        title: '警告',
        message: '退出后程序的所有服务将被关闭,你确定要退出吗？',
        noLink: true,
        icon: 'warning'
    }).then((response) => {
        if (response.response === 0) {
            // 用户点击了确定按钮
            // 执行退出应用
            app.exit();
        }
    }).catch((error) => {
        // 处理错误
    });
}